import Vue from 'vue';
let host = '';
let defaultLoading = false;
let afterRequest = () => {};
let beforeRequest = () => {};
let uploadDefault = '/app/member/index/upload.json';

function request(url, param, way, res) {
	const params = beforeRequest(url, param, way) || {};
	uni.request({
		url: host + url,
		data: param,
		header: {
			'xhrFields': {
				withCredentials: true
			}, //权限认证
			'Content-Type': "application/json", //传参类型
		},
		...params,
		method: way,
		success: (data) => {
			res(data.data)
		},
		fail: () => {
			res({
				data: {
					data: {},
					success: false,
					code: 500,
					msg: "请求失败"
				}
			})
		}
	});
}

function upload(params, url = uploadDefault) {
	console.log(params, url)
	uni.showLoading({
		mask: true,
		title: '正在上传'
	})
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: host + url,
			...params,
			success({data}) {
				resolve(JSON.parse(data))
			},
			fail: reject,
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}

export default {
	init(config) {
		console.log("*** http installed ***");
		defaultLoading = !!config.load;
		host = config.host || '/';
		uploadDefault = config.uploadDefault || uploadDefault;
		afterRequest = config.afterRequest || afterRequest;
		beforeRequest = config.beforeRequest || beforeRequest;
		
		Vue.prototype.$http = {
			request: this.request,
			upload: this.upload,
			getHost: this.getHost,
		}
	},
	request: async function(url, param, way = 'POST', showLoading) {
		const showLoad = typeof showLoading === 'boolean' ? showLoading : defaultLoading;
		if (showLoad)
			uni.showLoading({
				title: "正在加载",
				mask: true
			})
		return await new Promise(resolve => {
			request(url, param, way, (res) => {
				if (showLoad) uni.hideLoading()
				afterRequest(res)
				resolve(res)
			});
		})

	},
	upload,
	getHost() {
		return host;
	}
}
